package com.example.wenliangjiudian.service.impl;

import com.example.wenliangjiudian.entity.Role;
import com.example.wenliangjiudian.entity.User;
import com.example.wenliangjiudian.mapper.RoleMapper;
import com.example.wenliangjiudian.mapper.UserMapper;
import com.example.wenliangjiudian.mapper.UserRoleMapper;
import com.example.wenliangjiudian.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public User getByName(String username) {

        User user = userMapper.getByName(username);
        return user;
    }

    @Override
    public List<User> selectAll() {
        List<User> list = userMapper.selectAll();

        for (User user : list) {
            List<Role> roles = roleMapper.listRoleByUserId(user.getId());
            String roleNames = "";

            for (Role role : roles) {
                if (role == null || role.getName() == null) {
                    continue;
                }
                roleNames = roleNames + role.getName() + ",";
            }

            // 去掉最后一个逗号
            if (!roles.isEmpty() && roleNames.endsWith(",")) {
                roleNames = roleNames.substring(0, roleNames.lastIndexOf(','));
            }


            user.setRoleNames(roleNames);
        }
        return list;
    }

    @Override
    public void delete(Integer id) {
        userMapper.delete(id);

    }

    @Override
    public void add(User user) {
        if (user.getHeadurl() == null || user.getHeadurl() == "") {
            user.setHeadurl("https://img.alicdn.com/imgextra/i3/57350691/O1CN01Lhy0l01GyWPRZw60d_!!0-saturn_solar.jpg_468x468q75.jpg_.webp");
        }

        userMapper.add(user);
    }

    @Override
    public User getById(Integer id) {
        return userMapper.getById(id);
    }

    @Override
    public void update(User user) {
        userMapper.update(user);
    }

    @Override
    public void register(User user) {
        // 添加用户
        add(user);

        User byName = getByName(user.getUsername());

        // 给用户添加默认权限
        Integer userId = byName.getId();
        Integer roleId = 3;//默认，3：普通客户
        userRoleMapper.addUserRole(userId, roleId);
    }
}
